package cn.tedu.friend;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RelationReducer extends Reducer<Text,Text,Text,IntWritable> {

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        // key = tom values = rose jim smith locy
        // 记录真实好友关系
        String name = key.toString();
        IntWritable trueFriend = new IntWritable(1);
        List<String> fs = new ArrayList<>();
        for (Text value:values
             ) {
            String f = value.toString();
            fs.add(f);
            if (name.compareTo(f)<0)
                context.write(new Text(name+"-"+f),trueFriend);
            else
                context.write(new Text(f+"-"+name),trueFriend);
        }
        // 根据好友列表来推测好友之间是否认识
        IntWritable fakeFriend = new IntWritable(0);
        for (int i = 0; i < fs.size()-1; i++) {
            String f1 = fs.get(i);
            for (int j = i+1; j < fs.size(); j++) {
                String f2 = fs.get(j);
                if (f1.compareTo(f2)<0)
                    context.write(new Text(f1+"-"+f2),fakeFriend);
                else
                    context.write(new Text(f2+"-"+f1),fakeFriend);
            }
        }
    }
}
